<template>
  <div>
    <div class="gva-form-box">
      <el-form :model="formData" ref="elFormRef" label-position="right" :rules="rule" label-width="160px">
        <el-form-item label="短剧名称:" prop="movieId">
          <el-input v-model.number="formData.movieId" :clearable="true" placeholder="请输入"  :disabled = "true"/>
       </el-form-item>
        <el-form-item label="剧集id:" prop="episodeId">
          <el-input v-model.number="formData.episodeId" :clearable="true" placeholder="请输入" :disabled = "true" />
       </el-form-item>
        <el-form-item label="章节-序号:" prop="seq">
          <el-input v-model.number="formData.seq" :clearable="true" placeholder="请输入" :disabled = "true"/>
       </el-form-item>
        <el-form-item label="章节名称:" prop="seqName">
          <el-input v-model="formData.seqName" :clearable="true" placeholder="请输入" :disabled = "true"/>
       </el-form-item>
       <el-form-item label="平台类型:" prop="platId">
          <el-select v-model="formData.platId" placeholder="请选择" :clearable="false">
            <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
          </el-select>
       </el-form-item>
        <el-form-item label="推广名称:" prop="referralName">
          <el-input v-model="formData.referralName" :clearable="true" placeholder="请输入" />
       </el-form-item>
       
       <el-form-item label="自定义单集价格:"  prop="moviePrice" >
              <el-input v-model.number="formData.moviePrice" :clearable="true" placeholder="自定义单集价格（单位分）"  />
        </el-form-item>
        <el-form-item label="自定义免费集数:"  prop="epFreeNum" >
              <el-input v-model.number="formData.epFreeNum" :clearable="true" placeholder="自定义免费集数"  />
        </el-form-item>
        <el-form-item label="投放媒体:" prop="source">
          <el-radio-group v-model="formData.source">
            <el-radio label="dy">抖音</el-radio>
          </el-radio-group>
       </el-form-item>
       <el-form-item label="广告链路类型:" prop="adType">
        <el-radio-group v-model.number="formData.adType"    >
                <el-radio v-for="(item,key) in adTypeOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
       </el-form-item>
        <el-form-item label="回传分类:" prop="callbackType">
          <el-radio-group v-model="formData.callbackType">
            <el-radio :label="2">自定义方案</el-radio>
          </el-radio-group>
       </el-form-item>
       <el-form-item label="回传配置:"  prop="callbackConfigId" >
              <el-select
                v-model.number="formData.callbackConfigId"
                style="width:100%" placeholder="请选择回传配置"
                >
                  <el-option
                    v-for="item in convruleslist"
                    :key="item.ID"
                    :value="item.ID"
                    :label="item.name"
                  />
              </el-select>
            </el-form-item>
        <el-form-item label="充值模板类型:" prop="productType">
          <el-radio-group v-model="formData.productType">
            <!-- <el-radio :label="1">通用模板</el-radio> -->
            <el-radio :label="2">自定义模板</el-radio>
          </el-radio-group>
       </el-form-item>
        <el-form-item label="充值模板选择:" prop="productTplUserId">
          <el-select
                v-model.number="detailData.tplUserInfo"
                style="width:100%" 
                placeholder="请选择充值模板"
                @change="selectChanged"
                value-key="ID"
                >
                  <el-option
                    v-for="item in productTplUserList"
                    :key="item.ID"
                    :value="item"
                    :label="item.name"
                  />
          </el-select>
       </el-form-item>
        <!-- <el-form-item label="充值挽留 档位库id:" prop="productIdRetain">
          <el-input v-model="formData.productIdRetain" :clearable="true" placeholder="请输入" />
       </el-form-item> -->
       <el-form-item label="批量创建条数:" prop="batchCreateNum">
          <el-input v-model.number="formData.batchCreateNum"   />
       </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {
  createTReferral,
  updateTReferral,
  findTReferral,
  getConvRulesApi
} from '@/api/tReferral'


import {
  getTProductTplUserList
} from '@/api/tProductTplUser'

defineOptions({
    name: 'TReferralForm'
})

// 自动获取字典
import { getDictFunc } from '@/utils/format'
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'

const props = defineProps({
  row: {
    default: function() {
      return {}
    },
    type: Object
  }
})
const emit = defineEmits(['enterReferralAdd'])


const route = useRoute()
const router = useRouter()
const platOptions = ref([])
const adTypeOptions = ref([])


const type = ref('')
const formData = ref({
            platId: '',
            movieId: props.row.ID,
            episodeId: props.row.ID+1,
            seq: 1,
            seqName: '第1集',
            referralName: '',
            moviePrice: 150, 
            epFreeNum: 10, 
            source: 'dy', 
            callbackType: 2,
            callbackConfigId: '',
            productType: 2,
            productTplUserId: 0,
            productTplUserName: '',

            productIds: '',
            productOrder: '',
            productIdsPaid: '',
            productOrderPaid: '',
            productIdRetain: '',
            batchCreateNum:1,
            link: '',
            shortLink: '',
            adType:1,
            createUid: 0,
            createTime: '',
            updateUid: 0,
            updateTime: '',
        })
  const detailData = ref({
      productTplUserName: '',
      movieInfo:{},
      tplUserInfo:{}
  })
const moviePriceMinMax =  (rule, value, callback) => {
  if(value>350|| value<50) {
    callback('超出限制')
  } else {
    callback()
  }
}
const epFreeNumMinMax =  (rule, value, callback) => {
  if(value>30|| value<5) {
    callback('超出限制')
  } else {
    callback()
  }
}
const batchCreateNumMinMax =  (rule, value, callback) => {
  if(value>100|| value<1) {
    callback('超出限制')
  } else {
    callback()
  }
}
// 验证规则
const rule = reactive({
    movieId : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
    ],
    episodeId : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
    ],
    referralName : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
      {
        whitespace: true,
        message: '不能只输入空格',
        trigger: ['input', 'blur'],
      }
    ],
    platId : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
    ],
    productType : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
    ],
    productIds : [{
        required: true,
        message: '',
        trigger: ['input','blur'],
      },
    ],
    moviePrice : [{ 
        validator: moviePriceMinMax, 
        message: '自定义单集价格范围50-350或0',
        trigger: 'blur'
      },
      {type: 'number', message: '请输入数字', trigger: 'blur'}
    ],
    epFreeNum : [{ 
        validator: epFreeNumMinMax, 
        message: '自定义免费集数范围5-30或0',
        trigger: 'blur'
      },
      {type: 'number', message: '请输入数字', trigger: 'blur'}
    ],
    batchCreateNum : [{ 
        validator: batchCreateNumMinMax, 
        message: '批量生成个数范围 1-100',
        trigger: 'blur'
      },
      {type: 'number', message: '请输入数字', trigger: 'blur'}
    ],
})

const elFormRef = ref()

// 初始化方法
const init = async () => {
 // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
      const res = await findTReferral({ ID: route.query.id })
      if (res.code === 0) {
        formData.value = res.data.retReferral
        type.value = 'update'
      }
    } else {
      type.value = 'create'
    }
    platOptions.value = await getDictFunc('plat')
    adTypeOptions.value = await getDictFunc('adType')
}

init()
// 保存按钮
const save = async() => {
      elFormRef.value?.validate( async (valid) => {
         if (!valid) return
            let res
           switch (type.value) {
             case 'create':
               res = await createTReferral(formData.value)
               break
             case 'update':
               res = await updateTReferral(formData.value)
               break
             default:
               res = await createTReferral(formData.value)
               break
           }
           if (res.code === 0) {
             emit('enterReferralAdd', false)
             ElMessage({
               type: 'success',
               message: '创建/更改成功'
             })
           }
       })
}

// 返回按钮
const back = () => {
    router.go(-1)
}

const convruleslist = ref([])
const getConvRuleslist = async() => {
  const res = await getConvRulesApi()
  if (res.code === 0) {
    convruleslist.value = res.data.list
    formData.value.callbackConfigId = res.data.list[0].ID
  }
}
getConvRuleslist()


const productTplUserList = ref([])
const getProductTplUserList = async() => {
  const res = await getTProductTplUserList()
  if (res.code === 0) {
    productTplUserList.value = res.data.list
    formData.value.productTplUserId = res.data.list[0].ID
    formData.value.productIds=res.data.list[0].productIds
    formData.value.productOrder=res.data.list[0].productOrder
    formData.value.productIdsPaid=res.data.list[0].productIdsPaid
    formData.value.productOrderPaid=res.data.list[0].productOrderPaid

    detailData.value.tplUserInfo= res.data.list[0]


  }
}
getProductTplUserList()

const selectChanged = async (e)  => {
  formData.value.productTplUserId=e.ID
  formData.value.productIds=e.productIds
  formData.value.productOrder=e.productOrder
  formData.value.productIdsPaid=e.productIdsPaid
  formData.value.productOrderPaid=e.productOrderPaid
  formData.value.productTplUserName=e.name

  detailData.value.tplUserInfo=productTplUserList.value.filter(item => item.ID==e.ID )[0]

}
</script>

<style>
</style>
